/* eslint-disable no-await-in-loop */
/* eslint-disable max-len */
import React from 'react';

import { ReactComponent as Three } from '@/assets/images/profile/Button.svg';
import { ReactComponent as Chevron } from '@/assets/images/shared/icon-chevron.svg';
import { getAccessToken } from '@/entities/auth/model/selectors';
import { productApi } from '@/entities/course';
import { ChevronCard } from '@/entities/profile/ui/ChevronCard';
import { env, innerUrls } from '@/shared/constants';
import { makeMockArray } from '@/shared/lib/transformArrayIntoObject';
import { useAppDispatch, useAppSelector } from '@/shared/store';
import { Button, ButtonVariants, Loader } from '@/shared/ui';
import { PDFViewer } from '@/widgets/PDFViewer';
import classNames from 'classnames';
import { useRouter } from 'next/router';
import { useWindowSize } from 'usehooks-ts';

import { NoFiles } from '../../NoFiles';
import cs from './Info.module.scss';

export const Info = ({ openModal, isRating }: { openModal?: (i: boolean) => void; isRating?: boolean }) => {
  const token = useAppSelector(getAccessToken);
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { id } = router.query;
  const { data: order, isLoading } = productApi.useGetSingleOrderQuery(id as string, { skip: !id });

  const containerRef = React.useRef(null);
  const [isOpened, setIsOpen] = React.useState(false);

  const { width } = useWindowSize();
  const [init, setInit] = React.useState(false);
  const [currentPdf, setCurrentPdf] = React.useState<any>(null);
  const [currentPdfId, setCurrentPdfId] = React.useState<number | null>(null);
  const [loading, setLoading] = React.useState<boolean>();
  const fetchFile = async (attachmentId: number, courseId: number) => {
    if (isOpened) {
      setIsOpen(false);
    }
    setLoading(true);
    const response = await fetch(`${env.apiUrl}/courses/${courseId}/attachments/${attachmentId}`, {
      method: 'GET',
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });

    if (!response.ok) {
      throw new Error('Network response was not ok');
    }

    const reader = response.body?.getReader();

    if (!reader) {
      throw new Error('ReadableStream is not available');
    }
    const chunks: Uint8Array[] = [];
    const iter = 1;
    while (iter) {
      const { done, value } = await reader.read();

      if (done) {
        break;
      }

      if (value) {
        chunks.push(value);
      }
    }

    const blob = new Blob(chunks);

    setCurrentPdf(blob);
    setCurrentPdfId(attachmentId);
    setLoading(false);
  };

  React.useEffect(() => {
    setInit(true);
  }, []);

  const openNewWindow = (url: string) => {
    window.open(url, '_blank');
  };

  // React.useEffect(() => {
  //   if (width < 1024 && order?.items?.[0]?.product.course.attachments.length === 1 && init) {
  //     dispatch(setCurrentPDF(order?.items?.[0]?.product.course.attachments[0]));
  //   }
  // }, [width]);

  const currentAttachmentInformation = order?.items?.length
    ? order?.items[0]?.product?.course?.attachments.find((item) => item?.id === currentPdfId)
    : undefined;
  return (
    <>
      <div className={cs.block} ref={containerRef}>
        <span className={cs.title}>
          Читать
          {width < 1024 && (
            <div onClick={() => openModal?.(true)}>
              <Three className={cs.three} />
            </div>
          )}
        </span>
        {width < 1024 && order?.items[0]?.productId && !order.userRatingId && (
          <Button
            className={cs.btn}
            data-testid="button-create_review"
            href={innerUrls.boughtCourse('review', order?.items[0]?.productId)}
            link
            target="_blank"
            variant={ButtonVariants.Blue}
          >
            Оставить отзыв
          </Button>
        )}
        {!currentPdf && (
          <div className={cs.pdfs}>
            {order?.items[0]?.product.course.attachments.map((item) => (
              <ChevronCard
                courseId={order?.items[0].productId}
                item={item}
                key={item.id}
                openNewWindow={openNewWindow}
              />
            ))}
          </div>
        )}
        {!isLoading && currentPdf && !!order?.items?.[0]?.product?.course?.attachments?.length && width > 1024 && (
          <>
            <div className={classNames(cs.selectContainer, isOpened && cs.active)}>
              <Button
                className={cs.selectContainer}
                data-testid="button-open_pdf"
                onClick={() => setIsOpen((prev) => !prev)}
              >
                {currentAttachmentInformation?.name}
                <Chevron />
              </Button>
              {isOpened && width > 1024 && (
                <div className={cs.choose}>
                  {order?.items?.[0]?.product.course.attachments.map((item) => (
                    <Button
                      className={classNames(
                        cs.chooseItem,
                        currentAttachmentInformation?.name === item.name && cs.isActive,
                      )}
                      data-testid="link-open-pdf"
                      key={item.id}
                      onClick={() => fetchFile(item.id as number, order?.items?.[0].productId)}
                    >
                      {item.name}
                    </Button>
                  ))}
                </div>
              )}
            </div>
          </>
        )}

        {isLoading && (
          <div className={cs.pdfs}>
            {makeMockArray(4).map(({ id }) => (
              <Loader className={cs.chooseItem} height={76} key={id} />
            ))}
          </div>
        )}

        {!isLoading && !order?.items?.[0]?.product.course.attachments.length && (
          <NoFiles
            courseId={order?.items?.[0]?.productId as number}
            isRating={isRating}
            orderEmail={order?.email}
            status={order?.status?.id}
          />
        )}

        {/* {loading && (
          <div className={cs.loaderWrapper}>
            <RotationLoader />
          </div>
        )}

        {currentPdf && !loading && (
          <span
            className={cs.pdf_container}
            style={{
              marginTop: order?.items[0]?.product.course.attachments.length === 1 && width > 1024 ? '40px' : '0px',
            }}
          >
            <PDFViewer file={currentPdf} />
          </span>
        )} */}
      </div>
      {/* {width < 1024 && (
        <Modal isMobile isOpen={isOpened} onCloseClick={() => setIsOpen(false)}>
          <span className={cs.Title}>
            {order?.items[0]?.product.course.attachments.length}{' '}
            {declension(order?.items[0]?.product.course.attachments.length as number, ['гайд', 'гайда', 'гайдов'])} от companyName
          </span>
          <div className={cs.pdfs}>
            {order?.items[0]?.product.course.attachments.map((item) => (
              <div
                className={cs.desc}
                key={item.id}
                onClick={() => {
                  dispatch(
                    setCurrentPDF({
                      file: item.file || '',
                      name: item.name || '',
                    }),
                  );
                  setIsOpen(false);
                }}
              >
                {item.name}
                <Chevron />
              </div>
            ))}
          </div>
        </Modal>
      )} */}
    </>
  );
};
